package com.dyz.leetcode;

import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
import java.util.PriorityQueue;

public class MaxSlidingWindow239 {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int [] res = new int[nums.length-k+1];
        //堆排序O(nlongk) 超时
        PriorityQueue<Integer> pd = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        for (int i=0; i<k; i++){
            pd.add(nums[i]);
        }
        int index = 0;
        for(int i=k; i<=nums.length;i++){
            res[index++] = pd.peek();
            if(i!=nums.length){
                pd.remove(nums[i-k]);
                pd.add(nums[i]);
            }
        }
        return res;
    }
    public int[] maxSlidingWindow1(int[] nums, int k) {
        //单调队列
        int n = nums.length;
        Deque<Integer> deque = new LinkedList<Integer>();
        for (int i = 0; i < k; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
        }

        int[] ans = new int[n - k + 1];
        ans[0] = nums[deque.peekFirst()];
        for (int i = k; i < n; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
            while (deque.peekFirst() <= i - k) {
                deque.pollFirst();
            }
            ans[i - k + 1] = nums[deque.peekFirst()];
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1,3,-1,-3,5,3,6,7};
        new MaxSlidingWindow239().maxSlidingWindow1(nums, 3);
    }
}
